<?
// REQUIRED & INCLUDE FILES
if ($zdir == 1) { $pre = '../'; }
if ($exclude != 1) {
	require($pre."includes/date_parse.php");
	require($pre."includes/date_conversion.php");
	require($pre."includes/config.inc.php");
	include($pre."includes/sajax/sajax.php");
}	

// Check Page --------------------------------------------- //
$selfArray = explode("/", $_SERVER[PHP_SELF]);
$elements = count($selfArray);
$last_element = $elements - 1;
$file = $selfArray[$last_element];

// Check for page requiring logged in user
session_start();
if ( (empty($_SESSION['logged'])) && ($file != 'index.php') ) {
	header("Location: index.php");
}

$pathInfo = pathinfo($PHP_SELF);

// Check fields
function fieldToDB($string,$urlClick=null) {
	// Trim whitespace
		$string = trim($string);
	// Check for HTML characters
		$string = str_replace(Chr(10), '{lb}', $string);
		$string = str_replace('\r\n', '{lb}', $string);
		$string = htmlspecialchars($string,ENT_QUOTES,"UTF-8");
	// Make URL's clickable if required
		if ($urlClick == 1) {
			$string = parseURLS($string,false,'_blank');	
		}	
	
	// Prevent SQL injection
		$string = mysql_real_escape_string($string);	
	// Insert line breaks if needed
		$string = str_replace('{lb}', '<br>', $string);
	
	return $string;
}
function DBToField($string) {
	//$string = htmlspecialchars_decode($string,ENT_QUOTES);
	$string = str_replace('&quot;', '"', $string);
	// Insert line breaks
	$string = str_replace('<br>', chr(10), $string);
	$string = str_replace('<br>', '\n', $string);
	// Replace HTML entities characters with HTML
	$string = stripslashes($string);
	return $string;
}

function cleanString($fn) {
	global $cleanString;
		
	$fn = stripslashes($fn);	
	$patArray  = array('&#039;','&amp;','#','$',' ',Chr(39),Chr(35),Chr(38),'!','?','*','(',')',':',';','+','=');
	$replArray = array('','','','','-','','','','','','','','','','','','');
	
	$pats = count($patArray);
	
	for($a=0;$a<=($pats-1);$a++) {
		$fn = (str_replace($patArray[$a], $replArray[$a], $fn));
	} 
		
	$cleanString = $fn;
	return $cleanString;
}

// Great little function that converts plain text url's into clickable url's
// url's must be in the form of http://..... 
// By Nico : May be found at http://www.bytemycode.com/snippets/snippet/602/
function parseURLS($text, $maxurl_len = 35, $target = '_self') {
    if (preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si', $text, $urls)) {
        $offset1 = ceil(0.65 * $maxurl_len) - 2;
        $offset2 = ceil(0.30 * $maxurl_len) - 1;
       
        foreach (array_unique($urls[1]) AS $url) {
            if ($maxurl_len AND strlen($url) > $maxurl_len) {
                $urltext = substr($url, 0, $offset1) . '...' . substr($url, -$offset2);
            }
            else { $urltext = $url; }
           
            $text = str_replace($url, '<a href="'. $url .'" target="'. $target .'" title="'. $url .'">'. $urltext .'</a>', $text);
        }
    }
    return $text;
}

// Determine Browser
$browser = strstr(getenv('HTTP_USER_AGENT'), 'MSIE');
if (!empty($browser)) {
	// Check for Opera browser
	$opera = strstr(getenv('HTTP_USER_AGENT'), 'Opera');
	if (!empty($opera)) {
		$browser = "Mozilla"; 
		$stylesheet = "stylesMozilla.css?".random_string(5);
		$jpeg_mime_type = "image/jpeg";
	} else {
		$browser = "IE"; 
		$stylesheet = "stylesIE.css?".random_string(5);
		$jpeg_mime_type = "image/pjpeg";
	}	
} else {
	$browser = "Mozilla"; 
	$stylesheet = "stylesMozilla.css?".random_string(5);
	$jpeg_mime_type = "image/jpeg";
}

// Better mail function
function mailNew($fromName, $fromAddress, $to, $subject, $message) {
   // Copyright ? 2005 ECRIA LLC, http://www.ECRIA.com
   // Please use or modify for any purpose but leave this notice unchanged.
   $headers  = "MIME-Version: 1.0\n";
   $headers .= "Content-type: text/plain; charset=iso-8859-1\n";
   $headers .= "X-Priority: 3\n";
   $headers .= "X-MSMail-Priority: Normal\n";
   $headers .= "X-Mailer: php\n";
   $headers .= "From: \"".$fromName."\" <".$fromAddress.">\n";
   return mail($to,$subject,$message,$headers);
}

// Function to prevent email form injection attacks
function emailPreventInjection($input) {
	$repl = '';
	$input = (ereg_replace("\r", $repl, $input));
	$input = (ereg_replace("\n", $repl, $input));
	$input = (ereg_replace("%0a", $repl, $input));
	$input = (ereg_replace("%0d", $repl, $input));
	$input = (ereg_replace("Content-Type:", $repl, $input));
	$input = (ereg_replace("bcc:", $repl, $input));
	$input = (ereg_replace("to:", $repl, $input));
	$input = (ereg_replace("cc:", $repl, $input));
	return $input;
} 

function random_string($length) {
	global $string;
	// Generate Random Password
	mt_srand ((double) microtime() * 1000000);
	$possible = "ABCDEFGHJKLMNPQRSTUVWXYZ";
	$string = "";
	
	while (strlen($string) < $length) {
		$no_add = 0;
		$str = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
		// Check that preceeding character in $password is not same as current character
				
		if (strlen($string) >= 1) {
			for ($a=1;$a<=strlen($string);$a++) {
				// $str will be current character
				if ($str == substr("$string", -$a, 1)) { $no_add = 1; }
			} // End For Loop
		} // End If
		
		if ($no_add == 1) { continue; }
		$string .= $str; // Build the password string
	} // End While loop
	return $string;
}
// Function Resize_image()
// This function accepts a jpeg image, resizes it according to a scaling factor
// and then copies it to a new file with a specified filename "extension"
// Ex. resize_image(image.jpg, 100, thumb) 
// This would generate a new JPEG file called thumb_image.jpg at 100 pixels wide

function resize_image($orig_file,$max_width,$max_height,$file_ext,$dir,$border,$mime) {
	// Determine filenames
	$fileArray = explode("/", $orig_file);
	$file_elements = count($fileArray);
	$last_element = $file_elements - 1;
	if (!empty($file_ext)) {
		$out_file = $file_ext."_".$fileArray[$last_element];
	} else {
		$out_file = $fileArray[$last_element];
	}	
	
	// Rebuild directory string for thumbnail file
	$directory = "";
	for ($a=0;$a<=($last_element - 1);$a++) {
		if (empty($directory)) {
			$directory = $fileArray[$a];
		} else {
			$directory = $directory."/".$fileArray[$a];
		}		
	}
	if (!empty($dir)) { $directory = $directory."/".$dir; }
	
	$out_file = $directory."/".$out_file;	
		
	$size = getimagesize($orig_file);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		$im_in = imagecreatefromjpeg($orig_file);
	} elseif ($mime == "image/gif") {
		$im_in = imagecreatefromgif($orig_file);
	} elseif ($mime == "image/png") {
		$im_in = imagecreatefrompng($orig_file);
	}
	
	// Get original image dimentions
	$origW = $size[0];
	$origH = $size[1];
	
	// Get scale %age - we have 3 cases here
	if (!empty($max_width) && !empty($max_height)) {
		// This is gonna be tricky 'cause we want to avoid disportion
		// Do short side first, then figure out other dimention
		if ($origW > $origH) {
			// Horizontal orientation
			// Determine ideal scale
			$scale = floor($max_height / $origH);
			$new_height = $max_height;
			$new_width = $max_width;
			
			$optW = floor($origW*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origH;
				$cropH = $origH;							
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}		
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($orig_file);
			}						
				
		} elseif ($origW < $origH) {
			// Vertical orientation
			// Determine ideal scale
			$scale = floor($max_width / $origW);
			$new_width = $max_width;
			$new_height = $max_height;
			
			$optH = floor($origH*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origW;
				$cropH = $origW;							
				$origW = $cropW;
				$origH = $cropH;			
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}			
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($out_file);
			}			
		} elseif ($origW == $origH) {
			// Square - easy
			$new_width = $max_width;
			$new_height = $max_height;
		}
	} elseif (!empty($max_width) && empty($max_height)) {	
		$scale = ($max_width / $origW);
		$new_width = $max_width;
		$new_height = floor($origH * $scale);
	} elseif (!empty($max_height) && empty($max_width)) {
		$scale = ($max_height / $origH);
		$new_height = $max_height;
		$new_width = floor($origW * $scale);
	}
		
	$im_out = imagecreatetruecolor($new_width, $new_height);
	imagecopyresized($im_out, $im_in, 0, 0, 0, 0, $new_width, $new_height, $origW, $origH);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		imagejpeg($im_out, $out_file, 100);
	} elseif ($mime == "image/gif") {
		imagegif($im_out, $out_file, 100);
	} elseif ($mime == "image/png") {
		imagepng($im_out, $out_file, 100);
	}
	
	// Draw border
	if (!empty($border)) {
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			$im_in =  imagecreatefromjpeg($out_file);
		} elseif ($mime == "image/gif") {
			$im_in =  imagecreatefromgif($out_file);
		} elseif ($mime == "image/png") {
			$im_in =  imagecreatefrompng($out_file);
		}
		$color = ImageColorAllocate($im_in,0,0,0);
		ImageLine($im_in,0,0,($max_width-1),0,$color); // Top
		ImageLine($im_in,($max_width-1),1,($max_width-1),($max_height-1),$color); // Right
		ImageLine($im_in,($max_width-1),($max_height-1),1,($max_height-1),$color); // Bottom
		ImageLine($im_in,0,($max_height-1),0,0,$color); // Left
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			imagejpeg($im_in, $out_file, 100);
		} elseif ($mime == "image/gif") {
			imagegif($im_in, $out_file, 100);
		} elseif ($mime == "image/png") {
			imagepng($im_in, $out_file, 100);
		}
	}
	
	imagedestroy($im_out);
	imagedestroy($im_in);	
}

function replace_bad_chars($string) {
	global $new_string;
	$string = stripslashes($string);
	$new_string = $string;
	$badArray = array(Chr(47),Chr(34),Chr(35),Chr(39),Chr(32),Chr(92));
	$goodArray = array('','','','','_','');
	$elements = count($badArray);
	for($a=0;$a<=($elements-1);$a++) {
		$pat = $badArray[$a];
		$repl = $goodArray[$a];
		$new_string = (ereg_replace($pat, $repl, $new_string));
	}	
	return $new_string;
}

function daysBetweenDates($dateStart,$dateEnd) {
	global $days;
	$dateStartArray = explode("-",$dateStart);
	$dateEndArray = explode("-",$dateEnd);
	
	$startYear = $dateStartArray[0];
	$startMonth = $dateStartArray[1];
	$startDay = $dateStartArray[2];
	
	$endYear = $dateEndArray[0];
	$endMonth = $dateEndArray[1];
	$endDay = $dateEndArray[2];
	
	//first convert to unix timestamp
	$init_date = mktime(12,0,0,$startMonth,$startDay,$startYear);
	$dst_date = mktime(12,0,0,$endMonth,$endDay,$endYear);

	$offset = $dst_date-$init_date; //Depending on which offset type you want, switch order

	$days = floor($offset/60/60/24); 
	return $days;
}

function shortText($text,$words) {
	global $shortText;
	$text = strip_tags($text,'<a>');
	$textArray = explode(" ", $text);
	$newText = null;
	for($zz=0;$zz<=($words);$zz++) {
		$newText .= $textArray[$zz]." ";
	}
	$shortText = $newText."...";
	
	return $shortText;
}

function paginate($pages,$perPage,$urlString,$page,$pageNoOnly) {
	if ($pageNoOnly == 1) {
		echo "Page: ";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"$PHP_SELF?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
	} else {
		echo "<div class=\"grayField\" style=\"text-align: right;\">Page: \n";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"$PHP_SELF?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
		echo "</div>\n";
	}	
}

function microtime_float() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

// Hover grabs some text from the database based on ID and displays
// content in mouseover popup using overLib javaScript library.
function hoverHelp($type,$hoverID) {
	global $linkHREF, $dbname, $db, $db_selected;
	
	if ($type == "help") {
		// Get content from ss_help
		$sql = "SELECT DEFINITION from DICTIONARY WHERE WORD = '$word' LIMIT 1";
		$result = mysql_db_query($dbname,$sql);
		$rowDef = mysql_fetch_assoc($result);
	} elseif ($type == "message") {
		// Get content from ss_siteMessage
	}		
	$linkHREF = "<a href=\"\" onmouseover=\"return overlib('Hi there', STICKY, CENTER, MOUSEOFF, WRAP, CELLPAD, 5);\" onmouseout=\"return nd();\">\n";
	$defineLink .= "<b>$displayWord</b></a>";
	echo $linkHREF;
	return $linkHREF;
}

function buildBreadcrumbs($path) {
	global $breadCrumbs, $dbname, $db, $db_selected;
	// $path is in the form of /mainCat/subCat/subSubCat
	
	$pathArray = explode('/',$path);
	$mainCat   = $pathArray[1];
	$subCat    = $pathArray[2];
	$subSubCat = $pathArray[3];
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$mainCatName = stripslashes($row[LevelName]);
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$subCatName = stripslashes($row[LevelName]);
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat/$subSubCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$subSubCatName = stripslashes($row[LevelName]);
	
	if (empty($mainCatName) && empty($subCatName) && empty($subSubCatName)) {
		$breadCrumbs = '';
	} else {
		$breadCrumbs = '';
		if (!empty($mainCatName)) {
			$breadCrumbs .= $mainCatName.' ';
		} 
		if (!empty($subCatName)) {
			$breadCrumbs .= ': '.$subCatName.' ';
		}
		if (!empty($subSubCatName)) {
			$breadCrumbs .= ': '.$subSubCatName;
		}
	}
	return $breadCrumbs;
}

function listCatPaths($linkID) {
	global $catString, $dbname, $db, $db_selected;
	
	$sql = "SELECT TL.Path 
			FROM transLevels TL
			LEFT JOIN transLinkPath TLP ON TL.LevelID = TLP.PathID
			WHERE TLP.LinkID = '$linkID'";
	$result = mysql_db_query($dbname,$sql);
	$catString = '';	
		
	if (mysql_num_rows($result)>0) {
		while ($value = mysql_fetch_assoc($result)) {
			$fullPath = $value[Path];
			$fullPathText = buildBreadcrumbs($fullPath);
			$catString .= '<a href="http://www.tcntransition.org'.$fullPath.'">'.$fullPathText.'</a><br />';
		}
	}	
	return $catString;
}

function linkChecker($url) {
	global $html;
	$linkInfo  = @parse_url( $url );
	$fp = @fsockopen( $linkInfo["host"], 80, $errno, $errstr, 10 );
	if ( !$fp ) {
		return false;
	} else {
		if( empty( $linkInfo["path"] ) ) {
	        // If it is empty it fills it
	        $linkInfo["path"] = "/";
	     }
	     $query = "";
	
	     // Checks if there is a query string in the url
	     if( isset( $linkInfo["query"] ) ) {
	          // If there is a query string it adds a ? to the front of it
	          $query = "?".$linkInfo["query"]."";
	     }
	
	     // Sets the headers to send
	     $out  = "HEAD ".$linkInfo["path"]."".$query." HTTP/1.0\r\n";
	     $out .= "Host: ".$linkInfo["host"]."\r\n";
	     $out .= "Connection: close \r\n" ;
	     $out .= "User-Agent: link_checker/1.1\r\n\r\n";
	
	     // writes the headers out
	     @fwrite( $fp, $out );
	     $html = '';
	
	     // Reads what gets sent back
	     while ( !@feof( $fp ) ) {
	          $html .= @fread( $fp, 8192 );
	     }
	     // Closes socket
	     fclose( $fp );
	 }    
	 return $html;	
}
function getstatuscode( $header ) {
	global $status;
  // Splits the headers into an array
  $headers = explode( "\r\n", $header );
  unset( $header );
  for( $i=0;isset( $headers[$i] );$i++ ) {

    // Checks if the header is the status header
    if( preg_match( "/HTTP\/[0-9A-Za-z +]/i" ,$headers[$i] ) ) {

      // If it is save the status
      $status = preg_replace( "/http\/[0-9]\.[0-9]/i","",$headers[$i] );
    }
  }
  return $status;
}

function cleanFilename($fn) {
	global $filename;
		
	$fn = stripslashes($fn);	
	$patArray  = array('&#039;','&amp;','#','$',' ',Chr(39),Chr(35),Chr(38));
	$replArray = array('','','','','_','','','');
	
	$pats = count($patArray);
	
	for($a=0;$a<=($pats-1);$a++) {
		$fn = (ereg_replace($patArray[$a], $replArray[$a], $fn));
	} 
		
	$filename = $fn;
	return $filename;
}

function parse_csv_file($file, $columnheadings = false, $delimiter = ',', $enclosure = null) {
	global $rows;
   $row = 1;
   $rows = array();
   $handle = fopen($file, 'r');
  
   while (($data = fgetcsv($handle, 8000, $delimiter, $enclosure )) !== FALSE) {
       if ($columnheadings == true && $row == 1) {
           $headingTexts = $data;
       }
       elseif ($columnheadings == true) {
           foreach ($data as $key => $value) {
               unset($data[$key]);
               $data[$headingTexts[$key]] = $value;
           }
           $rows[] = $data;
       }
       else {
           $rows[] = $data;
       }
       $row++;
   }
  
   fclose($handle);
   return $rows;
}

function toolTip($ttLabel,$type=null) {
	global $toolTip,$dbname,$db,$db_selected,$pre;

	$sql = "SELECT * from ncdb_sysHelp WHERE BriefDesc = '$ttLabel'";
	$result = mysql_db_query($dbname,$sql);
	//$row = mysql_fetch_assoc($result);
	
	$ttText  = stripslashes($row[HelpText]);
	$type   = '0';
	$toolTip = '<SPAN onMouseOver="toolTip(\''.$ttText.'\',\''.$type.'\');" onMouseOut="toolTip()" style="cursor: help;"><img src="'.$pre.'images/icon_help_small.gif"></SPAN>';
	return $toolTip;
}

function extDateToMySQL($date=null) {
	// extDateToMySQL converts a date from the ext date-picker control to MySQL format 
	// MM/DD/YY --> YYYY-MM-DD
	
	if (empty($date)) { 
		$newDate = '0000-00-00';
	} else {
		$dateArray = explode('/',$date);
		$m = $dateArray[0];
		$d = $dateArray[1];
		$y = $dateArray[2];
		
		$newDate = $y.'-'.$m.'-'.$d;
	}	
	return $newDate;	
}

function mySQLToExt($date=null) {
	if ( ($date == '0000-00-00') || empty($date) ) {
		$newDate = '';
	} else {
		$dateArray = explode('-',$date);
		$y = $dateArray[0];
		$m = $dateArray[1];
		$d = $dateArray[2];
		
		$newDate = $m.'/'.$d.'/'.$y;
	}
	return $newDate;
}

function convertFileSize($inFileSize) {
	global $outFileSize;
	
	if ($inFileSize>999999) { $outFileSize = number_format( ($inFileSize/1000000),1).' MB'; }
	elseif ($inFileSize>999) { $outFileSize = number_format( ($inFileSize/1000),1).' KB'; }
	else { $outFileSize = number_format($inFileSize,1).' B';	}
	return $outFileSize;
}

function getCategories($display=null,$siteArea) {
	global $catString, $dbname, $db, $db_selected, $pre;
	
	$catString = '';
	// Get news and announcements
	$sql = "SELECT * from ncdb_MainCat WHERE SiteArea = '$siteArea' ORDER BY DisplayOrder";
	$result = mysql_db_query($dbname,$sql);
	
	while ($value = mysql_fetch_assoc($result)) {
		$catID   = $value[CatID];
		$catName = stripslashes($value[CatTitle]);
	
		if ($display == 'select') {
			$catString .= '<option value="'.$catID.'">'.$catName.'</option>';
		}
		
	}
	
	return $catString;
}

function exportResources($format=null,$pathID=null) {
	global $breadCrumbs, $downloadLink, $dbname, $db, $db_selected;
	
	// Open CSV file
	$filename = 'TCNResources';
	$csvFile = ROOT_DIR.'admin/downloads/'.$filename.'.'.$format;
	$csvFileHandle = fopen($csvFile, "w");
	$downloadLink = $filename.'.'.$format;	
	$header = '"Link ID","Path","Title","Description","URL","Date Added","Added By","Status"'.Chr(10);
	
	if ($pathID != 0) {
		// Get Path from LevelID
		$sql = "SELECT Path FROM transLevels WHERE LevelID = '$pathID'";
		$result = mysql_db_query($dbname,$sql);
		$row = mysql_fetch_assoc($result);
		$pathName = $row[Path];
		
		// Create full path
		$fullPath = buildBreadcrumbs($pathName);
		
		// Export only the given category of resources
		$sql = "SELECT TL.LinkID,TL.Title,TL.LinkDescription,TL.Link,TL.UserID,TL.DateCreated,TL.Status,TLI.FullName from transLinks TL
				LEFT JOIN transLinkPath LP ON TL.LinkID = LP.LinkID
				LEFT JOIN transLogin TLI ON TLI.UID = TL.UserID
				WHERE LP.PathID = '$pathID'
				ORDER BY TL.DateCreated DESC";
		$result = mysql_db_query($dbname,$sql);
		
		$body = '';
		while ($value = mysql_fetch_assoc($result)) {
			$linkID = $value[LinkID];
			$title  = $value[Title];
			$desc   = fieldToDB($value[LinkDescription]);
			$url    = $value[Link];	
			$date   = mysql_to_date2($value[DateCreated]);
			$fullName = $value[FullName];
			if ($value[Status] == 1) {
				$status = 'Active';
			} else {
				$status = 'Inactive';
			}
			$body .= '"'.$linkID.'","'.$fullPath.'","'.$title.'","'.$desc.'","'.$url.'","'.$date.'","'.$fullName.'","'.$status.'"'.Chr(10);
			
		}
			
		$csvFileContent = $header.$body;
	} else {
		// Export all resources
		$sql = "SELECT TL.LinkID,TL.Title,TL.LinkDescription,TL.Link,TL.UserID,TL.DateCreated,TL.Status,TLI.FullName,TLV.Path
				FROM transLinks TL
				LEFT JOIN transLinkPath LP ON TL.LinkID = LP.LinkID
				LEFT JOIN transLevels TLV ON TLV.LevelID = LP.PathID
				LEFT JOIN transLogin TLI ON TLI.UID = TL.UserID
				ORDER BY TLV.Path";
		$result = mysql_db_query($dbname,$sql);
		if (mysql_num_rows($result)>0) {			
			$body = '';
			$header = '"Link ID","Path","Full Path","Title","Description","URL","Date Added","Added By","Status"'.Chr(10);
	
			while ($value = mysql_fetch_assoc($result)) {
				$linkID   = $value[LinkID];
				$title    = $value[Title];
				$desc     = fieldToDB($value[LinkDescription]);
				$url      = $value[Link];	
				$date     = mysql_to_date2($value[DateCreated]);
				$pathName = $value[Path];
				$fullName = $value[FullName];				
				
				// Create full path
				$fullPath = buildBreadcrumbs($pathName);
		
				if ($value[Status] == 1) {
					$status = 'Active';
				} else {
					$status = 'Inactive';
				}
				$body .= '"'.$linkID.'","'.$pathName.'","'.$fullPath.'","'.$title.'","'.$desc.'","'.$url.'","'.$date.'","'.$fullName.'","'.$status.'"'.Chr(10);
			}
			
			$csvFileContent = $header.$body;			
		}		
	}
		
	// Close CSV File
	fwrite($csvFileHandle, $csvFileContent);
	fclose($csvFileHandle);
		
	return $downloadLink;
}

function search($searchTerm) {
	global $resourceString, $dbname, $db, $db_selected;
	
	$searchString = '';
	
	$sql = "SELECT * from transLinks 
			WHERE
				Title           LIKE '%$searchTerm%' OR
				LinkDescription LIKE '%$searchTerm%' OR 
				Link            LIKE '%$searchTerm%' 
			ORDER BY Title
			";
	$result = mysql_db_query($dbname,$sql);
	$results = mysql_num_rows($result);
	if ($results<1) {
		$resourceString .= 'No resources matched the search term <b>'.$searchTerm.'</b>.';
	} else {
		
		$i=1;
		while ($value = mysql_fetch_assoc($result)) {
			if (($i % 2) > 0) { $class = 'noRowClass'; }
			else { $class = "altRow"; }
			$linkID     = $value[LinkID];
			$linkTitle  = stripslashes($value[Title]);
			$linkDesc   = stripslashes($value[LinkDescription]);
			$linkDate   = $value[DateCreated];
			$linkURL    = $value[Link];
			$linkStatus = $value[Status];
			$linkViews  = $value[Views];
			$linkRankTotal = $value[RankTotal];
			$linkRanks  = $value[Ranks];
			$linkErrorCode  = $value[ErrorCode];
			$linkErrorLevel = $value[ErrorLevel];  
			$addUserID      = $value[UserID];
						
			// Get contributor name
			$sql2 = "SELECT FullName from transLogin WHERE UID = '$addUserID'";
			$result2 = mysql_db_query($dbname,$sql2);
			$rows = mysql_fetch_assoc($result2);
			$contributorName = $rows[FullName];
			if (empty($contributorName)) {
					$contributorName = 'Anonymous';
			}
			$contentArray = array(
									$class,
									$linkID,
									$linkTitle,
									$linkURL,
									$linkDesc,
									$linkDate,
									$linkViews,
									$contributorName,
									$linkStatus
								);
			$searchString .= renderResources($contentArray);
			$i++;
		}
		
	} // End ELSE
	$searchString .= '|'.$searchTerm.'|'.$results;
	return $searchString;
}

function renderResources($contentArray) {
	$class           = $contentArray[0];
	$linkID          = $contentArray[1];
	$linkTitle       = $contentArray[2];
	$linkURL         = $contentArray[3];
	$linkDesc        = $contentArray[4];
	$linkDate        = $contentArray[5];
	$linkViews       = $contentArray[6];	
	$contributorName = $contentArray[7];
	$linkStatus      = $contentArray[8];
	$errorStatus     = $contentArray[9];
	$errorDate       = $contentArray[10];
	$errorCode       = $contentArray[11];

	if ($linkStatus == 1) {
		// Link is active
		$statusIcon  = 'iconYes.gif';
		$statusTitle = 'Link is active: click to make inactive';  
	} else {
		// Link is inactive
		$statusIcon = 'iconNo.gif';
		$statusTitle = 'Link is inactive: click to make active'; 
		$linkStatus  = 0;
	}
	$catPaths = listCatPaths($linkID);
	if (empty($catPaths)) {
		$catPaths = 'No paths submitted';		
	}

	$resourceString .= '<div class="'.$class.'" id="row'.$linkID.'" onMouseOver="rowHoverControls('.$linkID.',\'on\');" onMouseOut="rowHoverControls('.$linkID.',\'off\',\''.$class.'\')">';
		$resourceString .= '<div style="padding: 3px; text-align: center; vertical-align: top; width: 50px; float: left;">';
			$resourceString .= '<div style="display: none;" id="control'.$linkID.'">';
			$resourceString .= '<a href="#" onClick="editResource('.$linkID.'); return false;"><img src="images/buttonEditBig.gif" style="border: none;" alt="Edit" /></a>';
			$resourceString .= '&nbsp;<a href="#" onClick="confirmDelete(\''.$linkID.'\',\'resource\'); return false;"><img src="images/buttonDeleteBig.gif" style="border: none;" alt="Delete" /></a>';
			$resourceString .= '</div>';
		$resourceString .= '</div><div style="width: 90%; float: left; padding: 3px;">';
	$resourceString .= '<p><span id="linkURL'.$linkID.'"><a href="'.$linkURL.'" target="_blank" title="View '.$linkTitle.'"><b>'.$linkTitle.'</b></a></span><br />
						<span id="linkDesc'.$linkID.'">'.$linkDesc.'</span></p>';
	$resourceString .= '<p><b>Submitted Under</b><br />';
	$resourceString .= $catPaths.'</p><br />';
	$resourceString .= '<div style="float: left; margin-right: 10px;" class="date">By '.$contributorName.' '.mysql_to_date2($linkDate).'</div>';					
	$resourceString .= '<div style="float: left; margin-right: 10px;" class="linkViews">Views '.$linkViews.'</div>';				
	$resourceString .= '<div style="float: left;" id="linkStatus'.$linkID.'"><img style="cursor: pointer;" onClick="toggleLinkStatus('.$linkID.','.$linkStatus.'); return false;" src="images/'.$statusIcon.'" title="'.$statusTitle.'" /></div>';
	$resourceString .= '<div style="clear: left;"></div>';
	
	if ($errorStatus == 1) {
		if ($errorCode == 'userbl') {
			$errorCode = 'User Notified';
		}
		$resourceString .= '<div style="color: red; font-weight: bold;">Error Code: '.$errorCode.' Reported on '.mysql_to_date2($errorDate).'</div>';
	}	
	$resourceString .= '</div><div style="clear: left; height: 10px;"></div></div>';

	return $resourceString;
}
?>